﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using HK2009.Common;
using HK2009.BusinessFacade;
using HK2009.BusinessFacadeHandler;
using HK2009.EntityQuery;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Text;
using System.Threading;

public partial class BookingNote_BookingNoteList : BasePage
{
    DataBase db = new DataBase();
    IBNBookingNoteHandler bookNoteManage = new BNBookingNoteHandler();
    ISyClientHandler clientManage = new SyClientHandler();
    ISystemHandler sysManage = new SystemHandler();
    private static bool isUpdate = false;
    private static bool isDel = false;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Session["UserID"] != null)
            {
                ISystemHandler sysManage = new SystemHandler();
                string strPermission = sysManage.GetLoginUserPermissions();
                if (!(strPermission.Contains("1053")))
                {
                    Response.Redirect("~/NotPurview.aspx");
                    return;
                }

                else
                {
                    //判断用户有没有添加托运单权限
                    if (strPermission.Contains("1054"))
                    {
                        lblBookingNoteEdit.Visible = true;
                    }
                    else
                    {
                        lblBookingNoteEdit.Visible = false;
                    }
                    //判断用户有没有修改托运单权限
                    if (strPermission.Contains("1055"))
                    {
                        isUpdate = true;
                        lbtnUpdates.Visible = true;
                    }
                    else
                    {
                        isUpdate = false;
                        lbtnUpdates.Visible = false;
                    }
                    //判断用户有没有删除托运单权限
                    if (strPermission.Contains("1056"))
                    {
                        isDel = true;
                        lbtnDelete.Visible = true;
                    }
                    else
                    {
                        isDel = false;
                        lbtnDelete.Visible = false;
                    }
                }
            }
            lbtnDelete.Attributes.Add("OnClick", "javascript:return confirm('" + Resources.Messages.DelRecord + "');");
            FillDDl();

            ViewState["OrderBy"] = "PKID";
            ViewState["Accending"] = "desc";          
            dataBind();    
        }
    }



    /// <summary>
    /// 处理传入参数。。返回SQL条件和sqlparameter
    /// </summary>
    /// <param name="sqlstr"></param>
    /// <param name="parms"></param>
    /// <summary>
    /// 处理传入参数。。返回SQL条件和sqlparameter
    /// </summary>
    /// <param name="sqlstr"></param>
    /// <param name="parms"></param>
    private void ProcessParms(ref string sqlstr, ref SqlParameter[] parms)
    {
        List<SqlParameter> list = new List<SqlParameter>();
        sqlstr = "";


        if (ViewState["Shipper"] != null)
        {
            // list.Add(new SqlParameter("@ShipperID", ViewState["ShipperID"].ToString()));
            sqlstr += " and ShipperID in (" + ViewState["Shipper"].ToString() + ")";
        }

        if (ViewState["Vendor"] != null)
        {
            list.Add(new SqlParameter("@VendorID", ViewState["Vendor"].ToString()));
            sqlstr += " and VendorID=@VendorID";

        }

        if (ViewState["Value"] != null)
        {
            if (ViewState["Name"].ToString().ToLower() == "shipperid" || ViewState["Name"].ToString().ToLower() == "customerid" || ViewState["Name"].ToString().ToLower() == "carrierforwar")
            {
                if (ViewState["Value"].ToString().EndsWith("%"))
                {
                    list.Add(new SqlParameter("@ColumnName", ViewState["Value"].ToString()));
                    sqlstr += " and " + ViewState["Name"].ToString() + " in(select PKID from Sy_Client where CNShortName like  @ColumnName + '%'  or ENGShortName like  @ColumnName + '%' or HKShortName like @ColumnName + '%')";
                }
                else
                {
                    list.Add(new SqlParameter("@ColumnName", ViewState["Value"].ToString()));
                    sqlstr += " and " + ViewState["Name"].ToString() + " in(select PKID from Sy_Client where CNShortName = @ColumnName  or ENGShortName = @ColumnName or HKShortName = @ColumnName)";

                }
            }
            else if (ViewState["Name"].ToString().ToLower() == "marketid")
            {
                if (ViewState["Value"].ToString().EndsWith("%"))
                {
                    list.Add(new SqlParameter("@ColumnName", ViewState["Value"].ToString()));
                    sqlstr += " and " + ViewState["Name"].ToString() + " in(select PKID from Sy_Market where CNName like @ColumnName + '%')";
                }
                else
                {
                    list.Add(new SqlParameter("@ColumnName", ViewState["Value"].ToString()));
                    sqlstr += " and " + ViewState["Name"].ToString() + " in(select PKID from Sy_Market where CNName = @ColumnName )";

                }

            }
            else if (ViewState["Name"].ToString().ToLower() == "destinationid")
            {
                if (ViewState["Value"].ToString().EndsWith("%"))
                {
                    list.Add(new SqlParameter("@ColumnName", ViewState["Value"].ToString()));
                    sqlstr += " and " + ViewState["Name"].ToString() + " in(select PKID from Sy_Destination where CNName like @ColumnName + '%' or HKName like @ColumnName + '%' or ENGName like @ColumnName + '%')";
                }
                else
                {
                    list.Add(new SqlParameter("@ColumnName", ViewState["Value"].ToString()));
                    sqlstr += " and " + ViewState["Name"].ToString() + " in(select PKID from Sy_Destination where CNName = @ColumnName  or HKName = @ColumnName  or ENGName = @ColumnName)";

                }
            }
            else if (ViewState["Name"].ToString().ToLower() == "shipperlmid")
            {
                if (ViewState["Value"].ToString().EndsWith("%"))
                {
                    list.Add(new SqlParameter("@ColumnName", ViewState["Value"].ToString()));
                    sqlstr += " and " + ViewState["Name"].ToString() + " in(select PKID from Sy_ClientLinkMan where LinkMan like @ColumnName + '%' and ClientID=BN.ShipperID) ";

                }
                else
                {
                    list.Add(new SqlParameter("@ColumnName", ViewState["Value"].ToString()));
                    sqlstr += " and " + ViewState["Name"].ToString() + " in(select PKID from Sy_ClientLinkMan where LinkMan = @ColumnName and ClientID=BN.ShipperID) ";

                }
                
            }

            else
            {
                if (ViewState["Value"].ToString().EndsWith("%"))
                {
                    list.Add(new SqlParameter("@ColumnName", ViewState["Value"].ToString()));
                    sqlstr += " and " + ViewState["Name"].ToString() + " like @ColumnName + '%'";
                }
                else
                {
                    list.Add(new SqlParameter("@ColumnName", ViewState["Value"].ToString()));
                    sqlstr += " and " + ViewState["Name"].ToString() + " = @ColumnName";

                }
            }
        }
        if (ViewState["Value2"] != null && ViewState["Value3"] != null)
        {
            list.Add(new SqlParameter("@DateFrom", ViewState["Value2"].ToString().ToString() ));
            list.Add(new SqlParameter("@DateTo",ViewState["Value3"].ToString() ));
            sqlstr += " and " + ViewState["Name2"].ToString() + " between @DateFrom and @DateTo ";
        }
        else if (ViewState["Value2"] != null && ViewState["Value3"] == null)
        {
            list.Add(new SqlParameter("@DateFrom", ViewState["Value2"].ToString().ToString() ));         
            sqlstr += " and " + ViewState["Name2"].ToString() + " >= @DateFrom ";
        }
        else if (ViewState["Value2"] == null && ViewState["Value3"] != null)
        {
            list.Add(new SqlParameter("@DateFrom", ViewState["Value3"].ToString().ToString() ));
            sqlstr += " and " + ViewState["Name2"].ToString() + " <= @DateFrom ";
        }
        if (ViewState["Status"] != null)
        {
            list.Add(new SqlParameter("@Status", ViewState["Status"].ToString()));
            sqlstr += " and Status = @Status";
        }

        if (sysManage.IsCompanyRoles2())//公司用户2
        {
            list.Add(new SqlParameter("@UserID", Session["UserID"].ToString()));

        }

        parms = list.ToArray();
    }
       

    private void dataBind()
    {
        string sqlStr = string.Empty;
        if (Session["UserID"] != null)
        {
            if (ViewState["Value"] != null && ViewState["Name"].ToString() == "ConfirmNO")
            {
                if (ViewState["Value"].ToString().EndsWith("%"))
                {

                    if (sysManage.IsCompanyRoles2())//公司用户2
                    {
                        sqlStr = @"SELECT distinct BN.*,(select CNShortName from Sy_Client as SC where SC.PKID=BN.ShipperID) as ShipperCNShortName ,
                        (select ENGShortName from Sy_Client as SC where SC.PKID=BN.ShipperID) as ShipperENGShortName,
                        (select HKShortName from Sy_Client as SC where SC.PKID=BN.ShipperID) as ShipperHKShortName,
                         (select top 1 ConfirmNO from BN_BookingNoteDtl where BookingNoteID=BN.PKID and ConfirmNo like @ColumnName +'%')as ConfirmNO,
                        (select LinkMan from Sy_ClientLinkMan as SM where SM.PKID=BN.ShipperLMID and SM.ClientID=BN.ShipperID) as ShipperLM FROM BN_BookingNote as BN 
                        inner join BN_BookingNoteDtl BNDtl on  BN.PKID=BNDtl.BookingNoteID 
                        where 1=1 
                        and BN.CreatedUser in(select UserID from Users where  ClientID in(select ClientID from Users where UserID=@UserID))";
                    }
                    else
                    {
                        sqlStr = @"SELECT distinct BN.*,(select CNShortName from Sy_Client as SC where SC.PKID=BN.ShipperID) as ShipperCNShortName ,
                        (select ENGShortName from Sy_Client as SC where SC.PKID=BN.ShipperID) as ShipperENGShortName,
                        (select HKShortName from Sy_Client as SC where SC.PKID=BN.ShipperID) as ShipperHKShortName,
                         (select top 1 ConfirmNO from BN_BookingNoteDtl where BookingNoteID=BN.PKID and ConfirmNo like @ColumnName +'%')as ConfirmNO,
                        (select LinkMan from Sy_ClientLinkMan as SM where SM.PKID=BN.ShipperLMID and SM.ClientID=BN.ShipperID) as ShipperLM FROM BN_BookingNote as BN inner join BN_BookingNoteDtl BNDtl on  BN.PKID=BNDtl.BookingNoteID  where 1=1 ";
                    }
                }
                else
                {
                    if (sysManage.IsCompanyRoles2())//公司用户2
                    {
                        sqlStr = @"SELECT distinct BN.*,(select CNShortName from Sy_Client as SC where SC.PKID=BN.ShipperID) as ShipperCNShortName ,
                        (select ENGShortName from Sy_Client as SC where SC.PKID=BN.ShipperID) as ShipperENGShortName,
                        (select HKShortName from Sy_Client as SC where SC.PKID=BN.ShipperID) as ShipperHKShortName,
                         (select top 1 ConfirmNO from BN_BookingNoteDtl where BookingNoteID=BN.PKID and ConfirmNo=@ColumnName) as ConfirmNO,
                        (select LinkMan from Sy_ClientLinkMan as SM where SM.PKID=BN.ShipperLMID and SM.ClientID=BN.ShipperID) as ShipperLM FROM BN_BookingNote as BN 
                        inner join BN_BookingNoteDtl BNDtl on  BN.PKID=BNDtl.BookingNoteID  
                        where 1=1 
                        and BN.CreatedUser in(select UserID from Users where  ClientID in(select ClientID from Users where UserID=@UserID))";
                    }
                    else
                    {
                        sqlStr = @"SELECT distinct BN.*,(select CNShortName from Sy_Client as SC where SC.PKID=BN.ShipperID) as ShipperCNShortName ,
                        (select ENGShortName from Sy_Client as SC where SC.PKID=BN.ShipperID) as ShipperENGShortName,
                        (select HKShortName from Sy_Client as SC where SC.PKID=BN.ShipperID) as ShipperHKShortName,
                         (select top 1 ConfirmNO from BN_BookingNoteDtl where BookingNoteID=BN.PKID and ConfirmNo=@ColumnName) as ConfirmNO,
                        (select LinkMan from Sy_ClientLinkMan as SM where SM.PKID=BN.ShipperLMID and SM.ClientID=BN.ShipperID) as ShipperLM FROM BN_BookingNote as BN inner join BN_BookingNoteDtl BNDtl on  BN.PKID=BNDtl.BookingNoteID  where 1=1 ";

                    }
                }
            }
            else
            {
                if (sysManage.IsCompanyRoles2())//公司用户2
                {
                    sqlStr = @"SELECT distinct BN.*,(select CNShortName from Sy_Client as SC where SC.PKID=BN.ShipperID) as ShipperCNShortName ,
                                (select ENGShortName from Sy_Client as SC where SC.PKID=BN.ShipperID) as ShipperENGShortName,
                                (select HKShortName from Sy_Client as SC where SC.PKID=BN.ShipperID) as ShipperHKShortName,
                                 (select top 1 ConfirmNO from BN_BookingNoteDtl where BookingNoteID=BN.PKID) as ConfirmNO,
                                (select LinkMan from Sy_ClientLinkMan as SM where SM.PKID=BN.ShipperLMID and SM.ClientID=BN.ShipperID) as ShipperLM FROM BN_BookingNote as BN 
                                inner join BN_BookingNoteDtl BNDtl on  BN.PKID=BNDtl.BookingNoteID   
                                 where 1=1 
                        and BN.CreatedUser in(select UserID from Users where  ClientID in(select ClientID from Users where UserID=@UserID))";
                }
                else
                {
                    sqlStr = @"SELECT distinct BN.*,(select CNShortName from Sy_Client as SC where SC.PKID=BN.ShipperID) as ShipperCNShortName ,
                        (select ENGShortName from Sy_Client as SC where SC.PKID=BN.ShipperID) as ShipperENGShortName,
                        (select HKShortName from Sy_Client as SC where SC.PKID=BN.ShipperID) as ShipperHKShortName,
                         (select top 1 ConfirmNO from BN_BookingNoteDtl where BookingNoteID=BN.PKID) as ConfirmNO,
                        (select LinkMan from Sy_ClientLinkMan as SM where SM.PKID=BN.ShipperLMID and SM.ClientID=BN.ShipperID) as ShipperLM FROM BN_BookingNote as BN inner join BN_BookingNoteDtl BNDtl on  BN.PKID=BNDtl.BookingNoteID   where 1=1 ";
                }
            }
            SqlParameter[] parms = null;
            string clause = string.Empty;
            ProcessParms(ref clause, ref parms);
            sqlStr += clause;

            DataTable dt = bookNoteManage.GetBookingNoteList(sqlStr, parms);
            DataView view = dt.DefaultView;
            view.Sort = ViewState["OrderBy"] + " " + ViewState["Accending"];
            gvBookNoteList.DataSource = view;
            gvBookNoteList.DataBind();
            if (dt != null && dt.Rows.Count > 0)
            {
                lblTotal.Text = dt.Rows.Count.ToString();
            }
            else
            {
                lblTotal.Text = "0";
            }
        }
    }
      
   
    protected void btnSearch_Click(object sender, EventArgs e)
    {

        if (lstSelShipper.Items.Count > 0)
        {
            string item = string.Empty;
            for (int i = 0; i < lstSelShipper.Items.Count; i++)
            {
                item += lstSelShipper.Items[i].Value + ",";
            }
            ViewState["Shipper"] = item.Substring(0, item.Length - 1);
        }
        else
        {
            ViewState["Shipper"] = null;
        }

        if (ddlVendor.SelectedValue != "0")
        {

            ViewState["Vendor"] = ddlVendor.SelectedValue;
        }
        else
        {
            ViewState["Vendor"] = null;
        }

        if (txtName.Text != string.Empty)
        {
            ViewState["Value"] = txtName.Text.Trim();
            ViewState["Name"] = ddlColumnName.SelectedValue;
        }
        else
        {
            ViewState["Value"] = null;
            ViewState["Name"] = null;
        }

        if (txtBetween.Text != string.Empty && txtTo.Text !=string.Empty)
        {
            ViewState["Value2"] = txtBetween.Text.Trim() + " 00:00:00";
            ViewState["Name2"] = ddlColumnName2.SelectedValue;
            ViewState["Value3"] = txtTo.Text.Trim() + " 23:59:59";
        }
        else if (txtBetween.Text != string.Empty && txtTo.Text == string.Empty)
        {
            ViewState["Value2"] = txtBetween.Text.Trim() + " 00:00:00";
            ViewState["Name2"] = ddlColumnName2.SelectedValue;
            ViewState["Value3"] = null;
        }
        else if (txtBetween.Text == string.Empty && txtTo.Text != string.Empty)
        {
            ViewState["Value2"] = null;
            ViewState["Name2"] = ddlColumnName2.SelectedValue;
            ViewState["Value3"] = txtTo.Text.Trim() + " 00:00:00";
        }
        else
        {
            ViewState["Value2"] = null;
            ViewState["Name2"] = null;
            ViewState["Value3"] = null;
        }


        if (radAll.Checked)
        {
            ViewState["Status"] = null;
        }
        else if (radInput.Checked)
        {
            ViewState["Status"] = Enums.BookingNoteStatus.NEW.ToString("d");
        }
        else if (radCheck.Checked)
        {
            ViewState["Status"] = Enums.BookingNoteStatus.CHECK.ToString("d");
        }
        else
        {
            ViewState["Status"] = Enums.BookingNoteStatus.CANCEL.ToString("d");

        }
        dataBind();
    }

    private void FillDDl()
    {
        //绑定托运人
        DataTable dt = clientManage.GetClientListByTypeID(int.Parse(Enums.CT.TYR.ToString("d")));
        lstShipper.DataSource = dt;

        if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("en"))
        {
            lstShipper.DataTextField = "ENGShortName";
        }
        else if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("zh-hk"))
        {
            lstShipper.DataTextField = "HKShortName";
        }
        else
        {
            lstShipper.DataTextField = "CNShortName";
        }
        lstShipper.DataValueField = "PKID";
        lstShipper.DataBind();

        //工厂
        dt = clientManage.GetClientListByTypeID(int.Parse(Enums.CT.GC.ToString("d")));
        //ddlVendor.DataSource = dt;
        //if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("en"))
        //{
        //    ddlVendor.DataTextField = "ENGShortName";
        //}
        ddlVendor.Items.Add(new ListItem(Resources.Messages.PleaseSelect, "0"));
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            ListItem item = new ListItem();
            if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("zh-hk"))
            {
                // ddlVendor.DataTextField = "HKShortName";
                item.Text = dt.Rows[i]["ENGShortName"].ToString() + "/" + dt.Rows[i]["HKShortName"].ToString();
            }
            else
            {
                item.Text = dt.Rows[i]["ENGShortName"].ToString() + "/" + dt.Rows[i]["CNShortName"].ToString();
                //ddlVendor.DataTextField = "CNShortName";
            }
            item.Value = dt.Rows[i]["PKID"].ToString();
            // ddlVendor.DataValueField = "PKID";
            ddlVendor.Items.Add(item);
        }
    }

    protected void lbtnGo_Click(object sender, EventArgs e)
    {
        TextBox txtPages = ((TextBox)gvBookNoteList.BottomPagerRow.FindControl("txtPages"));
        try
        {
            int i = Convert.ToInt32(txtPages.Text) - 1;
            if (i >= 0 && i < gvBookNoteList.PageCount)
            {
                this.gvBookNoteList.PageIndex = i;
                //数据绑定
                dataBind();
            }
            else
            {
                Jscript.AlertInAjax(Resources.Messages.WrongPageNumInput, UpdatePanel1);
                return;
            }
        }
        catch
        {
            Jscript.AlertInAjax(Resources.Messages.WrongPageNumInput, UpdatePanel1);
        }
    }
    protected void ddlPages_SelectedIndexChanged(object sender, EventArgs e)
    {
       gvBookNoteList.PageSize = int.Parse(ddlPages.SelectedValue);
       dataBind();
    }
    protected void gvBookNoteList_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvBookNoteList.PageIndex = e.NewPageIndex;
        dataBind();
    }
    protected void gvBookNoteList_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.ToLower() == "del")
        {
            BN_BookingNoteQuery bnQuerys = bookNoteManage.GetBookingNoteByPKID(int.Parse(e.CommandArgument.ToString()));
            if (bnQuerys != null)
            {
                //if (bnQuerys.Status.ToString() != Enums.BookingNoteStatus.CHECK.ToString("d"))
                //{


                string templeteDel = string.Empty;
                string emailToDel = string.Empty;
                List<string> emailList = new List<string>();
                string sqlStrSelect = string.Empty;
                sqlStrSelect = @"select * from BN_ShippingOrderDtl where BookingDtlID in(
                                    select PKID from BN_BookingDtl where BookingNoteDtlID in(
                                    select PKID from BN_BookingNoteDtl where BookingNoteID=@BookingNoteID))";
                SqlParameter[] parmsSelect = new SqlParameter[1];
                DataTable dtEmail = new DataTable();
                parmsSelect[0] = new SqlParameter("@BookingNoteID", e.CommandArgument.ToString());
                DataTable dtSeldel = db.RunSqlTab(sqlStrSelect, parmsSelect);
                if (dtSeldel != null && dtSeldel.Rows.Count > 0)//判断该托运单是否已经分配了job
                {

                    for (int i = 0; i < dtSeldel.Rows.Count; i++)
                    {
                        //读取运输队的联络人email
                        sqlStrSelect = @"select  * 
                                         FROM Sy_ClientLinkMan where ClientID=(select Contractor from BN_BookingDtl where PKID=
                                        (select BookingDtlID from BN_ShippingOrderDtl where PKID=@PKID))";


                        parmsSelect[0] = new SqlParameter("@PKID", dtSeldel.Rows[i]["PKID"].ToString());
                        dtEmail = db.RunSqlTab(sqlStrSelect, parmsSelect);
                        if (dtEmail != null && dtEmail.Rows.Count > 0)
                        {
                            foreach (DataRow row in dtEmail.Rows)
                            {
                                emailList.Add(row["Email"].ToString());
                            }
                        }
                    }
                }

                //判断该托运单是否已经确认了booking

                sqlStrSelect = @"select * from BN_BookingDtl where BookingNoteDtlID in(
                                    select PKID from BN_BookingNoteDtl where BookingNoteID=@BookingNoteID)";
                parmsSelect[0] = new SqlParameter("@BookingNoteID", e.CommandArgument.ToString());
                DataTable dtBookingSeldel = db.RunSqlTab(sqlStrSelect, parmsSelect);
                if (dtBookingSeldel != null && dtBookingSeldel.Rows.Count > 0)
                {
                    for (int i = 0; i < dtBookingSeldel.Rows.Count; i++)
                    {
                        //读取运输队的联络人email
                        sqlStrSelect = @"select  * 
                                         FROM Sy_ClientLinkMan where ClientID=(select Contractor from BN_BookingDtl where PKID=
                                        (select BookingDtlID from BN_ShippingOrderDtl where PKID=@PKID))";

                        parmsSelect[0] = new SqlParameter("@PKID", dtBookingSeldel.Rows[i]["PKID"].ToString());
                        dtEmail = db.RunSqlTab(sqlStrSelect, parmsSelect);
                        if (dtEmail != null && dtEmail.Rows.Count > 0)
                        {
                            foreach (DataRow row in dtEmail.Rows)
                            {
                                emailList.Add(row["Email"].ToString());
                            }
                        }
                    }
                }

                BN_BookingNoteQuery query = bookNoteManage.GetBookingNoteByPKID(int.Parse(e.CommandArgument.ToString()));


                //发email模板
                templeteDel += @"Hello, [title]: 



some reminds from special-line, 


[list]

     ";
                string dateFormat = "yyyy-MM-dd HH:mm:ss";
                string change = string.Empty;

                change = change + "InvoiceNO:" + query.InvoiceNO + @"

";

                change = change + "is delete by:" + Session["LoginID"].ToString() + @"

";

                templeteDel = templeteDel.Replace("[list]", change);


                foreach (string email in emailList)
                {
                    if (StringUtil.IsEmailAddress(email))
                    {
                        //templete = templete.Replace("[title]", email);
                        emailToDel += email + ",";
                    }
                }
                if (emailToDel != string.Empty)
                {
                    emailToDel = emailToDel.Substring(0, emailToDel.Length - 1) + ";";
                }
                templeteDel += "}";



                string sqlStr = string.Empty;
                //SqlParameter[] parms = new SqlParameter[1];
                //parms[0] = new SqlParameter("@BookingNoteID",bnQuerys.PKID.ToString());
                // = "select * from BN_BookingNoteDtl where BookingNoteID=@BookingNoteID";
                //DataTable dtBND = bookNoteManage.GetBookingNoteDetailList(sqlStr,parms);
                //if (dtBND != null && dtBND.Rows.Count > 0)
                //{
                //bool istrue=false;
                //for (int i = 0; i < dtBND.Rows.Count; i++)
                //{
                //    if (dtBND.Rows[i]["Status"].ToString() != Enums.BookingNoteDtlStatus.NEW.ToString("d") && dtBND.Rows[i]["Status"].ToString() != Enums.BookingNoteDtlStatus.CANCELBOOKING.ToString("d"))
                //    {
                //        istrue = true;
                //        break;
                //    }
                //}
                //if (istrue)
                //{
                //    Jscript.AlertInAjax(Resources.Messages.BookingnoteDtlNotDelete, UpdatePanel1);
                //    return;
                //}
                //else
                //{
                SqlParameter[] parmsDel = new SqlParameter[1];
                parmsDel[0] = new SqlParameter("@BookingNoteID", bnQuerys.PKID.ToString());

                sqlStr += @"delete from BN_ShippingOrderDtl where BookingDtlID in(
                                    select PKID from BN_BookingDtl where BookingNoteDtlID in(
                                    select PKID from BN_BookingNoteDtl where BookingNoteID=@BookingNoteID));";
                sqlStr += @"delete from BN_ShippingOrder where BookingID in(
                                    select BookingID from BN_BookingDtl where BookingNoteDtlID in(
                                    select PKID from BN_BookingNoteDtl where BookingNoteID=@BookingNoteID));";

                sqlStr += @"delete from BN_BookingDtl where BookingNoteDtlID in(
                                    select PKID from BN_BookingNoteDtl where BookingNoteID=@BookingNoteID);";
                sqlStr += @"delete from BN_Booking where PKID=(
                                    select BookingID from BN_BookingDtl where BookingNoteDtlID in(
                                    select PKID from BN_BookingNoteDtl where BookingNoteID=@BookingNoteID));";

                sqlStr += @"delete from BN_BookingNoteDtl where BookingNoteID=@BookingNoteID;";
                sqlStr += @"delete from BN_BookingNote where PKID=@BookingNoteID;";

                // sqlStr = "delete from BN_BookingNoteDtl where BookingNoteID=@BookingNoteID;delete from BN_BookingNote where PKID=@BookingNoteID";
                if (db.ExecSqlTransaction(sqlStr, parmsDel))
                {

                    if (templeteDel != string.Empty && emailToDel != string.Empty)
                    {

                        string[] temps = templeteDel.Substring(0, templeteDel.Length - 1).Split(new char[] { '}' });
                        string[] emails = emailToDel.Substring(0, emailToDel.Length - 1).Split(new char[] { ';' });
                        for (int i = 0; i < temps.Length; i++)
                        {
                            string[] ems = emails[i].Split(new char[] { ',' });
                            string subject = "reminds from special-line!";
                            for (int j = 0; j < ems.Length; j++)
                            {
                                SendMail send = new SendMail();
                                string content = temps[i].Replace("[title]", ems[j]);
                                send.MailBody = content;
                                send.MailSubject = subject;
                                send.MailTo = ems[j];

                                send.Send();
                            }
                        }
                    }

                    dataBind();
                }
                else
                {
                    Jscript.AlertInAjax(Resources.Messages.DeleteFailed, UpdatePanel1);
                }
                //}
                //}
            }
            //else
            //{
            //    Jscript.AlertInAjax(Resources.Messages.BookingnoteNotDelete, UpdatePanel1);
            //    return;
            //}
        }
        

    }
    protected void gvBookNoteList_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {           

            Label lblShipperCNShortName = (Label)e.Row.FindControl("lblShipperCNShortName");
            Label lblShipperHKShortName = (Label)e.Row.FindControl("lblShipperHKShortName");
            Label lblShipperENGShortName = (Label)e.Row.FindControl("lblShipperENGShortName");

            if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("en"))
            {
                lblShipperENGShortName.Visible = true;
                lblShipperCNShortName.Visible = false;
                lblShipperHKShortName.Visible = false;
              
            }
            else if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("zh-hk"))
            {
                lblShipperENGShortName.Visible = false;
                lblShipperCNShortName.Visible = false;
                lblShipperHKShortName.Visible = true;
            }
            else
            {
                lblShipperENGShortName.Visible = false;
                lblShipperCNShortName.Visible = true;
                lblShipperHKShortName.Visible = false;
            }

        }

    }
    protected void gvBookNoteList_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (e.SortExpression.ToLower() == ViewState["OrderBy"].ToString().ToLower())
        {
            if (ViewState["Accending"].ToString().ToLower() == "asc")
            {
                ViewState["Accending"] = "desc";
            }
            else
            {
                ViewState["Accending"] = "asc";
            }
        }
        else
        {
            ViewState["OrderBy"] = e.SortExpression;
        }

        dataBind();
    }

    public string GetTotalNum(object id)
    {
        return bookNoteManage.GetBookingNoteTotal(int.Parse(id.ToString())).ToString();
    }

    public string GetComplete(object id)
    {
        if (bookNoteManage.GetBookingNoteTotal(int.Parse(id.ToString())) > 0)
        {
            if (bookNoteManage.GetBookingNoteCompleteTotal(int.Parse(id.ToString())) == bookNoteManage.GetBookingNoteTotal(int.Parse(id.ToString())))
            {
                return Resources.Messages.Complete;
            }
            else
            {
                return bookNoteManage.GetBookingNoteCompleteTotal(int.Parse(id.ToString())).ToString() + "/" + bookNoteManage.GetBookingNoteTotal(int.Parse(id.ToString())).ToString();
            }
        }
        else
        {
            return "0";
        }
    }
   
    protected void lbtnUpdates_Click(object sender, EventArgs e)
    {
        if (Request["chkSelected"] != null)
        {
            Response.Redirect("BookingNoteUpdate.aspx?BookingNoteID=" + Request["chkSelected"]);
        }
        else
        {
            Jscript.AlertInAjax(Resources.Messages.PleaseSelect, UpdatePanel1);
        }
    }

    protected void lbtnDelete_Click(object sender, EventArgs e)
    {
        if (Request["chkSelected"] != null)
        {

            BN_BookingNoteQuery bnQuerys = bookNoteManage.GetBookingNoteByPKID(int.Parse(Request["chkSelected"]));
            if (bnQuerys != null)
            {
                //if (bnQuerys.Status.ToString() != Enums.BookingNoteStatus.CHECK.ToString("d"))
                //{


                string templeteDel = string.Empty;
                string emailToDel = string.Empty;
                List<string> emailList = new List<string>();
                string sqlStrSelect = string.Empty;
                sqlStrSelect = @"select * from BN_ShippingOrderDtl where BookingDtlID in(
                                    select PKID from BN_BookingDtl where BookingNoteDtlID in(
                                    select PKID from BN_BookingNoteDtl where BookingNoteID=@BookingNoteID))";
                SqlParameter[] parmsSelect = new SqlParameter[1];
                DataTable dtEmail = new DataTable();
                parmsSelect[0] = new SqlParameter("@BookingNoteID", Request["chkSelected"]);
                DataTable dtSeldel = db.RunSqlTab(sqlStrSelect, parmsSelect);
                if (dtSeldel != null && dtSeldel.Rows.Count > 0)//判断该托运单是否已经分配了job
                {

                    for (int i = 0; i < dtSeldel.Rows.Count; i++)
                    {
                        //读取运输队的联络人email
                        sqlStrSelect = @"select  * 
                                         FROM Sy_ClientLinkMan where ClientID=(select Contractor from BN_BookingDtl where PKID=
                                        (select BookingDtlID from BN_ShippingOrderDtl where PKID=@PKID))";


                        parmsSelect[0] = new SqlParameter("@PKID", dtSeldel.Rows[i]["PKID"].ToString());
                        dtEmail = db.RunSqlTab(sqlStrSelect, parmsSelect);
                        if (dtEmail != null && dtEmail.Rows.Count > 0)
                        {
                            foreach (DataRow row in dtEmail.Rows)
                            {
                                emailList.Add(row["Email"].ToString());
                            }
                        }
                    }
                }

                //判断该托运单是否已经确认了booking

                sqlStrSelect = @"select * from BN_BookingDtl where BookingNoteDtlID in(
                                    select PKID from BN_BookingNoteDtl where BookingNoteID=@BookingNoteID)";
                parmsSelect[0] = new SqlParameter("@BookingNoteID", Request["chkSelected"]);
                DataTable dtBookingSeldel = db.RunSqlTab(sqlStrSelect, parmsSelect);
                if (dtBookingSeldel != null && dtBookingSeldel.Rows.Count > 0)
                {
                    for (int i = 0; i < dtBookingSeldel.Rows.Count; i++)
                    {
                        //读取运输队的联络人email
                        sqlStrSelect = @"select  * 
                                         FROM Sy_ClientLinkMan where ClientID=(select Contractor from BN_BookingDtl where PKID=
                                        (select BookingDtlID from BN_ShippingOrderDtl where PKID=@PKID))";

                        parmsSelect[0] = new SqlParameter("@PKID", dtBookingSeldel.Rows[i]["PKID"].ToString());
                        dtEmail = db.RunSqlTab(sqlStrSelect, parmsSelect);
                        if (dtEmail != null && dtEmail.Rows.Count > 0)
                        {
                            foreach (DataRow row in dtEmail.Rows)
                            {
                                emailList.Add(row["Email"].ToString());
                            }
                        }
                    }
                }

                BN_BookingNoteQuery query = bookNoteManage.GetBookingNoteByPKID(int.Parse(Request["chkSelected"]));


                //发email模板
                templeteDel += @"Hello, [title]: 



some reminds from special-line, 


[list]

     ";
                string dateFormat = "yyyy-MM-dd HH:mm:ss";
                string change = string.Empty;

                change = change + "InvoiceNO:" + query.InvoiceNO + @"

";

                change = change + "is delete by:" + Session["LoginID"].ToString() + @"

";

                templeteDel = templeteDel.Replace("[list]", change);


                foreach (string email in emailList)
                {
                    if (StringUtil.IsEmailAddress(email))
                    {
                        //templete = templete.Replace("[title]", email);
                        emailToDel += email + ",";
                    }
                }
                if (emailToDel != string.Empty)
                {
                    emailToDel = emailToDel.Substring(0, emailToDel.Length - 1) + ";";
                }
                templeteDel += "}";



                string sqlStr = string.Empty;
                //SqlParameter[] parms = new SqlParameter[1];
                //parms[0] = new SqlParameter("@BookingNoteID",bnQuerys.PKID.ToString());
                // = "select * from BN_BookingNoteDtl where BookingNoteID=@BookingNoteID";
                //DataTable dtBND = bookNoteManage.GetBookingNoteDetailList(sqlStr,parms);
                //if (dtBND != null && dtBND.Rows.Count > 0)
                //{
                //bool istrue=false;
                //for (int i = 0; i < dtBND.Rows.Count; i++)
                //{
                //    if (dtBND.Rows[i]["Status"].ToString() != Enums.BookingNoteDtlStatus.NEW.ToString("d") && dtBND.Rows[i]["Status"].ToString() != Enums.BookingNoteDtlStatus.CANCELBOOKING.ToString("d"))
                //    {
                //        istrue = true;
                //        break;
                //    }
                //}
                //if (istrue)
                //{
                //    Jscript.AlertInAjax(Resources.Messages.BookingnoteDtlNotDelete, UpdatePanel1);
                //    return;
                //}
                //else
                //{
                SqlParameter[] parmsDel = new SqlParameter[1];
                parmsDel[0] = new SqlParameter("@BookingNoteID", bnQuerys.PKID.ToString());

                sqlStr += @"delete from BN_ShippingOrderDtl where BookingDtlID in(
                                    select PKID from BN_BookingDtl where BookingNoteDtlID in(
                                    select PKID from BN_BookingNoteDtl where BookingNoteID=@BookingNoteID));";
                sqlStr += @"delete from BN_ShippingOrder where BookingID in(
                                    select BookingID from BN_BookingDtl where BookingNoteDtlID in(
                                    select PKID from BN_BookingNoteDtl where BookingNoteID=@BookingNoteID));";

                sqlStr += @"delete from BN_BookingDtl where BookingNoteDtlID in(
                                    select PKID from BN_BookingNoteDtl where BookingNoteID=@BookingNoteID);";
                sqlStr += @"delete from BN_Booking where PKID=(
                                    select BookingID from BN_BookingDtl where BookingNoteDtlID in(
                                    select PKID from BN_BookingNoteDtl where BookingNoteID=@BookingNoteID));";

                sqlStr += @"delete from BN_BookingNoteDtl where BookingNoteID=@BookingNoteID;";
                sqlStr += @"delete from BN_BookingNote where PKID=@BookingNoteID;";

                // sqlStr = "delete from BN_BookingNoteDtl where BookingNoteID=@BookingNoteID;delete from BN_BookingNote where PKID=@BookingNoteID";
                if (db.ExecSqlTransaction(sqlStr, parmsDel))
                {

                    if (templeteDel != string.Empty && emailToDel != string.Empty)
                    {

                        string[] temps = templeteDel.Substring(0, templeteDel.Length - 1).Split(new char[] { '}' });
                        string[] emails = emailToDel.Substring(0, emailToDel.Length - 1).Split(new char[] { ';' });
                        for (int i = 0; i < temps.Length; i++)
                        {
                            string[] ems = emails[i].Split(new char[] { ',' });
                            string subject = "reminds from special-line!";
                            for (int j = 0; j < ems.Length; j++)
                            {
                                SendMail send = new SendMail();
                                string content = temps[i].Replace("[title]", ems[j]);
                                send.MailBody = content;
                                send.MailSubject = subject;
                                send.MailTo = ems[j];

                                send.Send();
                            }
                        }
                    }

                    dataBind();
                }
                else
                {
                    Jscript.AlertInAjax(Resources.Messages.DeleteFailed, UpdatePanel1);
                }
                //}
                //}
            }
            //else
            //{
            //    Jscript.AlertInAjax(Resources.Messages.BookingnoteNotDelete, UpdatePanel1);
            //    return;
            //}


        }

        else
        {
            Jscript.AlertInAjax(Resources.Messages.PleaseSelect, UpdatePanel1);
        }
    }

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        if (lstShipper.SelectedValue != string.Empty)
        {
            for (int i = 0; i < lstShipper.Items.Count; i++)
            {
                bool issel = false;
                if (lstShipper.Items[i].Selected)
                {
                    for (int j = 0; j < lstSelShipper.Items.Count; j++)
                    {
                        if (lstShipper.Items[i].Value == lstSelShipper.Items[j].Value)
                        {
                            issel = true;
                            break;
                        }
                    }

                    if (!issel)
                    {
                        ListItem item = new ListItem();
                        item.Text = lstShipper.Items[i].Text;
                        item.Value = lstShipper.Items[i].Value;
                        lstSelShipper.Items.Add(item);
                    }
                }
            }
           
        }
        else
        {

        }

    }
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        if (lstSelShipper.Items.Count > 0)
        {
            ListItemCollection lstColl = new ListItemCollection();
            for (int i = 0; i < lstSelShipper.Items.Count; i++)
            {
                if (!lstSelShipper.Items[i].Selected)
                {
                    ListItem item = new ListItem(lstSelShipper.Items[i].Text, lstSelShipper.Items[i].Value);
                    lstColl.Add(item);
                }
            }
            if (lstColl != null && lstColl.Count > 0)
            {
                lstSelShipper.Items.Clear();
                for (int j = 0; j < lstColl.Count; j++)
                {
                    lstSelShipper.Items.Add(lstColl[j]);
                }
            }
            else
            {
                lstSelShipper.Items.Clear();
            }

        }
    }
}
